package com.heima.search.service.impl;

import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.model.search.pojos.ApAssociateWords;
import com.heima.search.service.ApAssociateWordsService;
import com.heima.utils.common.Trie;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.lang.ref.SoftReference;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @作者 itcast
 * @创建日期 2021/4/25 15:12
 **/
@Service
public class ApAssociateWordsServiceImpl implements ApAssociateWordsService, InitializingBean {
    @Autowired
    MongoTemplate mongoTemplate;
    /**
     * 强引用:   类  变量 =  new 对象   就算内存满了 要溢出强引用关系还在
     * 软引用:  SoftReference<变量>   当内存要溢出前，会先释放所有软引用变量
     * 弱引用:
     * 虚引用:
     * */
    public static SoftReference<Trie> associateWordsTrie = null ;

    @Override
    public ResponseResult findAssociate(UserSearchDto userSearchDto) {
        //1 参数检查
        if(userSearchDto == null || StringUtils.isBlank(userSearchDto.getSearchWords())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2 执行查询 模糊查询
        List<ApAssociateWords> wordsList = mongoTemplate.find(Query.query(Criteria.where("associateWords")
                .regex(".*" +userSearchDto.getSearchWords()+ ".*")), ApAssociateWords.class);
        return ResponseResult.okResult(wordsList);
    }

    @Override
    public ResponseResult findAssociateV2(UserSearchDto userSearchDto) {
        //1 参数检查
        if(userSearchDto == null || StringUtils.isBlank(userSearchDto.getSearchWords())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2 执行查询 模糊查询
        if(associateWordsTrie == null || associateWordsTrie.get()==null){
            initTrieData();
        }
        Trie trie = associateWordsTrie.get();
        List<String> words = trie.getData(userSearchDto.getSearchWords());
        if(words!=null && words.size()>0){
            List<ApAssociateWords> collect = words.stream().map(word -> {
                ApAssociateWords associateWords = new ApAssociateWords();
                associateWords.setAssociateWords(word);
                return associateWords;
            }).collect(Collectors.toList());
            return ResponseResult.okResult(collect);
        }
        return ResponseResult.okResult();
    }


    /**
     * 初始化字段树的数据
     */
    public void initTrieData(){
        List<ApAssociateWords> words = mongoTemplate.findAll(ApAssociateWords.class);
        Trie trie = new Trie();
        if(words!=null && words.size()>0){
            words.stream().map(ApAssociateWords::getAssociateWords).forEach(trie::insert);
        }
        associateWordsTrie = new SoftReference<>(trie);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println(" trie 数据被初始化   ========================================>");
        // spring所管理的对象，的初始化方法
        initTrieData();
    }
}
